package com.android.egoaccel;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

/**
 * Records Acceleration Values and stores them to disk.
 * @author hasanshabih
 * */
public class MainActivity extends Activity implements SensorEventListener{
	
	private TextView XAxis, YAxis, ZAxis;
	private Button StartAccelerometer, StopAccelerometer, ExitApp;
	private float X,Y,Z;
	private long timestamp;
	private SensorManager mSensorManager;
	private ValueStorage mValueStorage;
	private Intent mIntent;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Tell sensor manager what service to associate itself with
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        // Initialize the storage component
        mValueStorage = new ValueStorage();
        // Intent needed to put application in background
        mIntent = new Intent(Intent.ACTION_MAIN);
        mIntent.addCategory(Intent.CATEGORY_HOME);
        mIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // UI Binding, Name and logic setting of various elements.
        BindElementsWithId();
        SetTextViewNames();
        SetButtonNames();
        SetButtonLogic();
    }
    
    /**
     * Sets the default texts of the TextViews
     * */
    private void SetTextViewNames() {
    	XAxis.setText("X:No Value");	YAxis.setText("Y:No Value");	ZAxis.setText("Z:No Value");
	}

	/**
     * Binds the elements with the IDs on the layout.
     * */
    private void BindElementsWithId(){
    	XAxis = (TextView) findViewById(R.id.textView1);
        YAxis = (TextView) findViewById(R.id.textView2);
        ZAxis = (TextView) findViewById(R.id.textView3);
        
        StartAccelerometer = (Button) findViewById(R.id.button1);
        StopAccelerometer = (Button) findViewById(R.id.button2);
        ExitApp = (Button) findViewById(R.id.button3);
    }

    /**
     * Set the text to be displayed on the buttons
     * */
    private void SetButtonNames(){
    	StartAccelerometer.setText("Start Accelerometer");
    	StopAccelerometer.setText("Stop Accelerometer");
    	ExitApp.setText("Exit");
    	// When App starts, there is no point in having the Stop Accelerometer Button enabled
		StartAccelerometer.setEnabled(true);
		StopAccelerometer.setEnabled(false);
    }
    
    /**
     * Sets the logic of what will happen when the buttons are clicked
     * */
    private void SetButtonLogic(){
    	StartAccelerometer.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// When start accelerometer is clicked, the accelerometer is registered with the
				// sensor manager and also the stop button is enabled.
				RegisterAccelerometerListener();
				StartAccelerometer.setEnabled(false);
				StopAccelerometer.setEnabled(true);
				Log.i("CD/MainActivity", "Accelerometer Started");
			}
		});
    	
    	StopAccelerometer.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// when stop accelerometer is clicked, the accelerometer is decoupled with the
				// sensor manager and also the start button is enabled. The text views are also
				// reset.
				UnregisterAccelerometerListener();
				StartAccelerometer.setEnabled(true);
				StopAccelerometer.setEnabled(false);
				SetTextViewNames();
				Log.e("CD/MainActivity", "Accelerometer Stopped");
			}
		});
    	
    	ExitApp.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// Call to finish the activity is issued
				Log.e("CD/MainActivity", "onDestroy()");
				onDestroy();
			}
		});
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

	@Override
	public void onAccuracyChanged(Sensor sensor, int accuracy) {}

	@Override
	public void onSensorChanged(SensorEvent event) {
		// get the values of the acceleration from all the axes and also the time stamp
		// at which these values are recorded and 
		X = event.values[0];	Y = event.values[1];	Z = event.values[2];
		timestamp = event.timestamp;
		XAxis.setText("X:"+X);	YAxis.setText("Y:"+Y);	ZAxis.setText("Z:"+Z);
		mValueStorage.PushNewTuple(timestamp, X, Y, Z);
	}
	
	/**
	 * Asks SensorManager to register the accelerometer and start listening.
	 * */
	private void RegisterAccelerometerListener() {
		mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
	}
	
	/**
	 * Tells Sensor Manager to stop listening to the Accelerometer
	 * */
	private void UnregisterAccelerometerListener(){
		mSensorManager.unregisterListener(this);
	}
	
	@Override
	public void onDestroy(){
		super.onDestroy();
		UnregisterAccelerometerListener();
		mValueStorage.InformThread(true);
		startActivity(mIntent);
	}
	
	@Override
	public void onPause(){
		super.onPause();
	}
	
	@Override
	public void onStop(){
		super.onStop();
	}
    
	@Override
	public void onResume(){
		super.onResume();
		mValueStorage.InformThread(false);
	}
}
